package com.heima.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojo.ApAssociateWords;
import com.heima.search.pojo.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: JW
 * @Description: TODO
 * @DateTime: 2022-02-18 16:01
 **/
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {


    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * @param userSearchDto
     * @Author: JW
     * @Description: TODO 联想词查询
     * @Date: 16:02 2022-02-18
     * @Param: [userSearchDto]
     * @return: com.heima.model.common.dtos.ResponseResult
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {

        //参数校验
        if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //分页检查
        if (userSearchDto.getPageSize() > 20) {
            userSearchDto.setPageSize(20);
        }

        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(Query.query(Criteria
                .where("associateWords").regex(".*?\\" + userSearchDto.getSearchWords() + ".*"))
                .with(Sort.by(Sort.Order.desc("createdTime"))), ApAssociateWords.class);

        return ResponseResult.okResult(apAssociateWords);
    }
}
